<template>
  <div :class="showHomeLogo()?'header-between':'header-end'">
    <div v-if="showHomeLogo()" class="home-logo" @click="toHomePage">
      <n-button text>
        <n-icon :component="Home" size="25"></n-icon>
      </n-button>
    </div>
    <div class="user-or-login">
      <n-popover v-if="checkLogin()">
        <template #trigger>
          <n-avatar round>{{ getStorageObject('userInfo').nickName }}</n-avatar>
        </template>
        <div class="flex-center-content">
          <p>uid: {{ getStorageObject('userInfo').uid }}</p>
          <n-button text @click="toSpacePage">个人中心</n-button>
        </div>
        <template #footer>
          <div class="flex-center-content">
            <n-button type="primary" @click="logoutHandler">退出</n-button>
          </div>
        </template>
      </n-popover>
      <n-popover v-else>
        <template #trigger>
          <n-avatar round>游客</n-avatar>
        </template>
        <div class="flex-center-content">
          <p>登陆体验更多功能</p>
        </div>
        <template #footer>
          <div class="flex-center-content">
            <n-button type="primary" @click="toLoginPage">登陆</n-button>
          </div>
        </template>
      </n-popover>
    </div>
  </div>
  <n-divider/>
</template>

<script setup>
import {useRouter} from "vue-router";
import {getStorageObject, delStorageItem} from "../../utils/localStorage.js";
import {checkLogin} from "../../utils/utils.js"
import {logout} from "../../api/userApi.js";
import {inject} from "vue";
import {Home} from "@vicons/tabler"

const reload = inject('reload')

const router = useRouter()

function showHomeLogo() {
  return router.currentRoute.value.fullPath !== '/'
}

function toLoginPage() {
  router.push({path: '/login', query: {target: router.currentRoute.value.fullPath}})
}

function toSpacePage() {
  if (router.currentRoute.value.fullPath === '/space') {
    reload()
  } else {
    router.push('/space')
  }
}

function toHomePage() {
  if (router.currentRoute.value.fullPath === '/') {
    reload()
  } else {
    router.push('/')
  }
}

function logoutHandler() {
  logout().then(resp => {
    delStorageItem('token')
    delStorageItem('userInfo')
    toHomePage()
  }).catch(err => {
    console.log(err)
  })
}

</script>

<style scoped>
.header-between {
  display: flex;
  justify-content: space-between;
  justify-items: center;
}
.header-end {
  display: flex;
  justify-content: flex-end;
  justify-items: center;
}

.user-or-login {
  right: 0;
}

.home-logo {
  left: 0;
}

.flex-center-content {
  display: flex;
  justify-content: center;
  flex-direction: column;
}
</style>